package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    @RequiresPermissions(value = {"department:list", "部门列表"}, logical = Logical.OR)
    public String list(Model model, QueryObject queryObject) {
        Employee currentUser = UserContext.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        PageInfo departmentList = departmentService.list(queryObject);
        model.addAttribute("result", departmentList);
        return "department/list"; // /WEB-INF/views/department/list.jsp
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"department:input", "部门编辑"}, logical = Logical.OR)
    public String input(Long id, Model model) {
        if (id != null) { // 点击了修改按钮过来
            Department department = departmentService.get(id);
            model.addAttribute("department", department);
        }
        return "department/input"; // /WEB-INF/views/department/input.jsp
    }


    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"department:saveOrUpdate", "部门保存/更新"}, logical = Logical.OR)
    public JsonResult saveOrUpdate(Department department) {
        if (department.getId() == null) { // 代表新增
            departmentService.save(department);
        } else { // 代表修改
            departmentService.update(department);
        }
        return new JsonResult();
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"department:delete", "部门删除"}, logical = Logical.OR)
    public JsonResult delete(Long id) {
        departmentService.delete(id);
        return new JsonResult();
    }
}
